package 二叉树;

public class LC_222完全二叉树的节点个数 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public int countNodes(TreeNode root) {
        //后序遍历
        if(root==null) return 0;
        //满二叉树遍历
        TreeNode left=root.left;
        TreeNode right=root.right;
        int leftdepth=0,rightdepth=0;
        while(left!=null){
            left=left.left;
            leftdepth++;
        }
        while(right!=null){
            right=right.right;
            rightdepth++;
        }
        if(leftdepth==rightdepth)
            return (2<<leftdepth)-1;
        int leftnum=countNodes(root.left);
        int rightnum=countNodes(root.right);
        return leftnum+rightnum+1;
//        return countNodes(root.left)+countNodes(root.right)+1;
     }
}
